from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import BasicAuthentication
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.permissions import IsAuthenticated
from rest_framework.filters import SearchFilter,OrderingFilter
from .sers import *
from mutils import SMSCode
import mutils
from .other import *
# Create your views here.
class CodeAPIView(APIView):
    def post(self,request):
        ser=CodeSer(data=request.data)
        ser.is_valid(raise_exception=True)
        phone=ser.validated_data.get("phone")

        #不真的发 不需要联网
        sms=SMSCode()
        code=sms.random_code()
        Code.objects.create(phone=phone,code=code)
        return Response({"验证码":code})


        #真的发 需要联网
        # sms=SMSCode()
        # code=sms.send(phone)
        # if code['status']==0:
        #     Code.objects.filter(phone=phone, code=sms.code)
        #     return Response({"验证码":sms.code,"msg":"发送成功"})
        # return Response({"msg":code['msg']})

class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSer

class TokenAPVIew(APIView):
    authentication_classes = [BasicAuthentication]
    def post(self,request):
        key=str(datetime.datetime.now())
        key=mutils.md5(key)

        Token.objects.update_or_create(user=request.user,defaults=({"key":key}))
        return Response({"token":key})


class BookViewSet(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSer
    authentication_classes = [BasicAuthentication]
    throttle_classes = [MyUserRate,MyAnonRate]
    pagination_class = Page
    filter_backends = [DjangoFilterBackend,SearchFilter,OrderingFilter]
    search_fields=['name']
    ordering_fields=['name']
    filter_class=BookFitlerSet


